<?php

namespace App\Traits;

use App\Models\Base\Regions;
use GuzzleHttp\Client;

/**
 * Http 请求封装 Trait
 *
 * @author: WangBin
 * @date: 2021/9/17
 */
trait HttpRequestTrait
{

    //$regions = $this->sendGet('http://jisuarea.market.alicloudapi.com/area/all', ['Authorization' => 'APPCODE ce1ffb4d375447329459f030294e82f7']);
    //$regions = $regions->getBody()->getContents();
    //$regions = json_decode($regions, true);
    //foreach ($regions['result'] as $region) {
    //Regions::saveData(
    //['region_id' => $region['id'], 'name' => $region['name'], 'parent_id' => $region['parentid'], 'parent_name' => $region['parentname'], 'district_code' => $region['districtcode'], 'area_code' => $region['areacode'], 'zipcode' => $region['zipcode'], 'depth' => $region['depth']]
    //);
    //}
    //return true;

    /**
     * 发送 GET 请求
     *
     * @param string $url
     * @param array $headers
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function sendGet(string $url, array $headers = [])
    {
        $params = ["verify"=>false, 'timeout' => 5];
        if(!empty($headers)) {
            $params['headers'] = $headers;
        }
        $client = new Client($params);
        return $client->get($url);
    }

    /**
     * 发送 POST 请求
     *
     * @param string $url
     * @param array $postData
     * @param array $headers
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function sendPost(string $url, array $postData = [], array $headers = [])
    {
        $params = ["verify"=>false, 'timeout' => 5];
        $fixHeader = ['Content-Type' => 'application/json'];
        if(!empty($headers)) {
            $fixHeader = array_merge($fixHeader, $headers);
        }
        $client = new Client();
        return $client->post($url, [
            'json' => $postData,
            'headers' => $fixHeader,
            // 'proxy' => $proxy
        ]);
    }
}
